package com.wdd.recoveryvehicle.loginUser.service.impl;

import com.wdd.common.auth.TokenGenerator;
import com.wdd.common.utils.DateTimeUtil;
import com.wdd.recoveryvehicle.sysToken.bean.SysToken;
import com.wdd.recoveryvehicle.loginUser.service.TokenService;
import com.wdd.recoveryvehicle.sysToken.service.SysTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {

    private Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);
    @Autowired
    private SysTokenService sysTokenService;

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    /**
     * 生成一个token
     *
     * @param userId
     * @return Result
     */
    public Map<String, Object> createToken(String userId) {
        Map<String, Object> result = new HashMap<>();
        //生成一个token
        String token = TokenGenerator.generateValue();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        //判断是否生成过token
        SysToken tokenEntity = sysTokenService.selectSysTokenByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new SysToken();
            tokenEntity.setUser_id(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdate_time(DateTimeUtil.dateToString8(now));
            tokenEntity.setExpire_time(DateTimeUtil.dateToString8(expireTime));
            //保存token
            sysTokenService.insertSysToken(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdate_time(DateTimeUtil.dateToString8(now));
            tokenEntity.setExpire_time(DateTimeUtil.dateToString8(expireTime));
            //更新token
            sysTokenService.updateSysTokenByUserId(tokenEntity);
        }
        result.put("token", token);
        result.put("expire", EXPIRE);
        return result;
    }

    public void logout(String token) {
        SysToken byToken = selectSysTokenByToken(token);
        //生成一个token
        token = TokenGenerator.generateValue();
        //修改token
        SysToken tokenEntity = new SysToken();
        tokenEntity.setUser_id(byToken.getUser_id());
        tokenEntity.setToken(token);
        sysTokenService.deleteSysTokenByUserId(byToken.getUser_id());
    }

    public SysToken selectSysTokenByToken(String accessToken) {
        return sysTokenService.selectSysTokenByToken(accessToken);
    }


}
